import threading
import time

from flask import Flask
from flask_cors import CORS
from flask_migrate import Migrate
from settings import Config
from db_init import db
from swaager_init import siwa
from tools.login_init import login
from flask_socketio import SocketIO


class CreateFlask:
    _app = None
    lock = threading.Lock()

    @property
    def app(self):
        return self._app

    @property
    def socket(self):
        return self._socket

    def __new__(cls, *args, **kwargs):
        with cls.lock:
            if not cls._app:
                time.sleep(0.05)
                app = Flask(__name__)
                socket = SocketIO(app, cors_allowed_origins="*",
                                  async_mode='eventlet', ping_interval=4)
                login.init_app(app)
                app.config.from_object(Config)
                app.secret_key = 'syl'
                migrate = Migrate()
                CORS(app)
                db.init_app(app=app)
                migrate.init_app(app, db)
                siwa.init_app(app)
                cls._app = app
                cls._socket = socket

        return super().__new__(cls, *args, **kwargs)


flask_obj = CreateFlask()
